<template>
    <div class="app-container">
        <div class="filter-container" style="display: flex;align-items: center;justify-content: space-between;">
            <div>
                <el-button size="mini" class="filter-item" style="margin-left: 10px;" type="primary"
                    @click="handleCreate">
                    新增题目
                </el-button>
                <el-button size="mini" class="filter-item" style="margin-left: 10px;" type="success">
                    导入题目
                </el-button>
                <el-button size="mini" class="filter-item" style="margin-left: 10px;" type="danger">
                    删除题目
                </el-button>
            </div>
            <div>
                <el-select v-model="listQuery.status" size="mini" style="width: 140px;margin-right: 10px;"
                    class="filter-item" @change="handleFilter">
                    <el-option v-for="(item,k) in typeOptions" :key="k" :label="item" :value="k">
                        <span style="float: left">{{ item }}</span>
                    </el-option>
                </el-select>
                <el-input v-model="listQuery.title" size="mini" placeholder="标题" style="width: 200px;"
                    class="filter-item" @keyup.enter.native="handleFilter" />
                <el-button v-waves size="mini" class="filter-item" type="primary" icon="el-icon-search"
                    @click="handleFilter">
                    搜索
                </el-button>
            </div>
        </div>

        <el-table :key="tableKey" ref="multipleTable" @selection-change="handleSelectionChange" v-loading="listLoading"
            :data="list" border fit highlight-current-row style="width: 100%;">
            <el-table-column type="selection" width="55">
            </el-table-column>
            <el-table-column label="类型" prop="id" align="center" width="80">
                <template slot-scope="{row}">
                    <span>{{ row.type | typeFilter }}</span>
                </template>
            </el-table-column>
            <el-table-column label="title" prop="id" >
                <template slot-scope="{row}">
                    <div v-html="row.title"></div>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
                <template slot-scope="{row,$index}">
                    <el-button type="primary" size="mini" @click="handleUpdate(row)">
                        编辑
                    </el-button>
                    <el-popconfirm style="margin-left: 10px;" title="是否要删除该记录" @onConfirm="handleDelete(row,$index)">
                        <el-button v-if="row.status!='deleted'" slot="reference" size="mini" type="danger">
                            删除
                        </el-button>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
            @pagination="getList" />

        <el-dialog :title="textMap[dialogStatus]" fullscreen :visible.sync="dialogFormVisible">
            <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="70px"
                style="margin-left:50px;">
                <el-form-item label="标题" prop="title">
                    <tinymce-plus width="100%" v-model="temp.title"></tinymce-plus>
                </el-form-item>
                <el-form-item label="题型" prop="type">
                    <el-radio-group v-model="temp.type" @change="changeType">
                        <el-radio-button v-for="(item,key) in typeOptions" :key="key" :label="key">
                            {{item}}
                        </el-radio-button>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="题目答案">
                    <el-table :data="temp.value.options" style="width: 100%" border>
                        <el-table-column label="是否答案" align="center" width="80" v-if="temp.type!=='trueOrfalse'&&temp.type!=='answer'">
                            <template slot-scope="{row,$index}">
                                <el-radio v-if="temp.type==='radio'||temp.type==='trueOrfalse'" v-model="temp.value.value" :label="$index">
                                    {{$index|indexFilter}}
                                </el-radio>
                                <el-checkbox v-else-if="temp.type==='checkbox'" v-model="temp.value.value"  :label="$index">{{$index|indexFilter}}</el-checkbox>
                                <span v-else>{{$index+1}}</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="答案">
                            <template slot-scope="{row,$index}">
                                <tinymce-plus width="100%" v-model="temp.value.options[$index]"></tinymce-plus>
                            </template>
                        </el-table-column>
                        <el-table-column width="80" align="center" v-if="temp.type!=='trueOrfalse'&&temp.type!=='answer'">
                            <template slot-scope="{row,$index}">
                                <el-popconfirm style="margin-left: 10px;" title="是否要删除该答案"
                                    @onConfirm="deleteQuestion($index)">
                                    <span slot="reference" class="el-icon-delete-solid"></span>
                                </el-popconfirm>
                            </template>
                        </el-table-column>
                    </el-table>
                    <div v-if="temp.type!=='trueOrfalse'&&temp.type!=='answer'" class="add-questionval" @click="addQuestion">
                        + 添加一个答案
                    </div>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">
                    返回
                </el-button>
                <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
                    提交
                </el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    import waves from '@/directive/waves' // waves directive
    import TinymcePlus from '@/components/TinymcePlus'
    import {
        fetchQuestion,
        createQuestion,
        updateQuestion,
        deleteQuestion
    } from '@/api/question'

    import Pagination from '@/components/Pagination' // secondary package based on el-pagination

    const statusOptions = {
        0: '已下架',
        1: '已上架'
    }
    const typeOptions = {
        radio: "单选题",
        checkbox: "多选题",
        trueOrfalse: "判断题",
        answer: "问答题",
        completion: "填空题"
    }
    const indexOptions = {
        0: 'A',
        1: 'B',
        2: 'C',
        3: 'D',
        4: 'E',
        5: 'F',
        6: 'J',
        7: 'H',
        8: 'I',
        9: 'K',
        10: 'L'
    }
    const valOptions = {
                radio: {
                    value: 0,
                    options: ['选项1', '选项2'],
                },
                checkbox: {
                    value: [0, 1],
                    options: ['选项1', '选项2', '选项3']
                },
                trueOrfalse: {
                    value: 0,
                    options: ['选项1', '选项2', '选项3']
                },
                answer: {
                    options: ['答案内容']
                },
                completion: {
                    options: ['填空答案1', '填空答案二', '填空答案3']
                }
            }
    export default {
        name: 'ComplexTable',
        model: {
            prop: 'value',
            event: 'input'
        },
        components: {
            Pagination,
            TinymcePlus
        },
        directives: {
            waves
        },
        filters: {
            typeFilter(type) {
                return typeOptions[type]
            },
            indexFilter(val) {
                return indexOptions[val]
            }
        },
        data() {
            return {
                dialogVisible: false,
                disabled: false,
                tableKey: 0,
                list: null,
                total: 0,
                listLoading: true,
                listQuery: {
                    page: 1,
                    limit: 20,
                    status: undefined,
                    title: undefined,
                    sort: '+id'
                },
                importanceOptions: [1, 2, 3],
                typeOptions,
                showReviewer: false,
                temp: {
                    id: undefined,
                    title: undefined,
                    value: {
                        value: 0,
                        options: ['选项1', '选项2'],
                    },
                    type: 'radio',
                    remark: '',
                },
                dialogFormVisible: false,
                dialogStatus: '',
                textMap: {
                    update: '修改',
                    create: '创建'
                },

                rules: {
                    title: [{
                        required: true,
                        message: '标题不能为空',
                        trigger: 'blur'
                    }],
                },
                multipleSelection: []

            }
        },
        created() {
            this.getList()
        },
        methods: {
            changeType(e){
                // 防止 连续传值
                this.temp.value=JSON.parse(JSON.stringify(valOptions[e].options))
            },
            deleteQuestion(index) {
                this.temp.value.options.splice(index, 1)
            },
            addQuestion() {
                this.temp.value.options.push('')
            },
            getList() {
                this.listLoading = true
                console.log(this.listQuery)
                fetchQuestion(this.listQuery).then(response => {
                    this.list = response.data.items
                    this.total = response.data.total
                    // Just to simulate the time of the request
                    setTimeout(() => {
                        this.listLoading = false
                    }, 1.5 * 1000)
                })
            },
            handleFilter() {
                this.listQuery.page = 1
                this.listQuery.status = parseInt(this.listQuery.status)
                this.getList()
            },
            handleModifyStatus(row, status) {
                this.$message({
                    message: '操作Success',
                    type: 'success'
                })
                row.status = status
            },
            handleSelectionChange(val) {
                this.multipleSelection = val;
            },
            resetTemp() {
                this.temp = {
                    id: undefined,
                    title: undefined,
                    value: {
                        value: 0,
                        options: ['选项1', '选项2'],
                    },
                    type: 'radio',
                    remark: '',
                }
            },
            handleCreate() {
                this.resetTemp()
                this.dialogStatus = 'create'
                this.dialogFormVisible = true
                this.$nextTick(() => {
                    this.$refs['dataForm'].clearValidate()
                })
            },
            createData() {
                this.$refs['dataForm'].validate((valid) => {
                    if (valid) {
                        this.temp.id = parseInt(Math.random() * 100) + 1024 // mock a id
                        this.temp.author = 'vue-element-admin'
                        createQuestion(this.temp).then(() => {
                            this.list.unshift(this.temp)
                            this.dialogFormVisible = false
                            this.$notify({
                                title: 'Success',
                                message: 'Created Successfully',
                                type: 'success',
                                duration: 2000
                            })
                        })
                    }
                })
            },
            handleUpdate(row) {
                this.temp = Object.assign({}, row) // copy obj
                this.temp.timestamp = new Date(this.temp.timestamp)
                this.dialogStatus = 'update'
                this.dialogFormVisible = true
                this.$nextTick(() => {
                    this.$refs['dataForm'].clearValidate()
                })
            },
            updateData() {
                this.$refs['dataForm'].validate((valid) => {
                    if (valid) {
                        const tempData = Object.assign({}, this.temp)
                        tempData.timestamp = +new Date(tempData
                            .timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
                        updateQuestion(tempData).then(() => {
                            const index = this.list.findIndex(v => v.id === this.temp.id)
                            this.list.splice(index, 1, this.temp)
                            this.dialogFormVisible = false
                            this.$notify({
                                title: 'Success',
                                message: 'Update Successfully',
                                type: 'success',
                                duration: 2000
                            })
                        })
                    }
                })
            },
            handleDelete(row, index) {
                deleteQuestion(tempData).then(() => {
                    this.$notify({
                        title: '成功提示',
                        message: '删除成功',
                        type: 'success',
                        duration: 2000
                    })
                    console.log(row)
                    this.list.splice(index, 1)
                })

            }
        }
    }

</script>
<style>
    .add-questionval {
        text-align: center;
        border: 1px dotted;
        padding: 10px;
        color: #1890ff;
        cursor: pointer;
    }

    .add-questionval:hover {
        background-color: #fffde7;
    }
</style>